package com.example.module_motocircle.ui.search

import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.forEachIndexed
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.lib_common.Router
import com.example.lib_common.Router.Ui.ArticleDetailsActivity
import com.example.lib_common.Router.Ui.GuideDetailsActivity
import com.example.lib_common.Router.Ui.InformationDetailActivity
import com.example.lib_common.Router.Ui.PostDetailsActivity
import com.example.lib_common.Router.Ui.SearchRetActivity
import com.example.lib_common.Router.Ui.TopicActivity
import com.example.lib_common.base.BaseActivity
import com.example.lib_common.base.BaseToolBarActivity
import com.example.lib_common.base.state.Empty
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.IRetryClickListener
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.Success
import com.example.lib_common.base.state.UILoader
import com.example.lib_common.base.state.UIState
import com.example.lib_common.dp
import com.example.lib_common.flow_eventbus.observe.observeEvent
import com.example.lib_common.flow_eventbus.post.postEvent
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.utils.IntentData
import com.example.lib_common.utils.LoggerUtils
import com.example.lib_common.utils.ToastUtils
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.ActivitySearchBinding
import com.example.module_motocircle.databinding.LayoutRefreshRecyclerviewBinding
import com.example.module_motocircle.dialog.MessageNoticeDialog
import com.example.module_motocircle.model.HotListItem
import com.example.module_motocircle.model.HotListType
import com.example.module_motocircle.ui.MotorCircleViewModel
import com.example.module_motocircle.ui.search.adatpter.MySocialConfig
import com.example.module_motocircle.ui.search.adatpter.SearchSuggestionEvent
import com.example.module_motocircle.ui.search.adatpter.SearchSuggestionsFragment
import com.example.module_motocircle.ui.search.adatpter.SelectPostTopicEvent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.log


@FlowPreview
@AndroidEntryPoint
//@Route(path = Router.Ui.SearchActivity)
class SearchActivity : BaseToolBarActivity<SearchViewModel, ActivitySearchBinding>(), View.OnClickListener {

     val mViewModel: SearchViewModel by viewModels()

    override val mLayoutResId: Int
        get() = R.layout.activity_search


     val mSearchSuggestionsFragment by lazy {
        SearchSuggestionsFragment.newInstance(mOnlyTopic)
    }

    //ARouter.getInstance().build(Router.Ui.SearchActivity)
    //                .withString(IntentData.KEY_SEARCH_TYPE, "all")
    //                .navigation()
//    @Autowired(name = IntentData.KEY_SEARCH_TYPE)
//    lateinit var mSearchType: String


     var mOnlyTopic = false

    //记录原始窗口高度
     var mWindowHeight = 0

     val mTextColorResId by lazy {
        val typedValue = TypedValue()
        this.theme.resolveAttribute(R.attr.colorText, typedValue, true)
        typedValue.resourceId
    }

    override fun initView() {
        super.initView()
        showSoftKeyBoard(mBinding.etSearch)
        //mOnlyTopic = (mSearchType == "topic")
        mOnlyTopic= false
        supportFragmentManager.beginTransaction().add(R.id.l_container, mSearchSuggestionsFragment, SearchSuggestionsFragment.TAG)
            .hide(mSearchSuggestionsFragment)
            .commitAllowingStateLoss()
    }



    //搜索话题页面的状态
    private fun onShowSearchTopic() {
        mBinding.run {
            lSearchHistory.visibility = View.GONE
            lHotTopic.visibility = if (mViewModel.mHotTopic.isEmpty()) View.GONE else View.VISIBLE
            mViewModel.mHotTopic.forEach {
                mBinding.flowHotTopic.addView(createFlowItem(it, true))
            }
            flowHotTopic.forEachIndexed { index, view ->
                view.setOnClickListener {
                    postEvent(SelectPostTopicEvent(mViewModel.mHotTopic[index].name, mViewModel.mHotTopic[index].id))
//                    Log.d("sss", mViewModel.mHotTopic[index].name)
//                    Log.d("sss", mViewModel.mHotTopic[index].id)
                    finish()
                }
            }

            lHotPost.visibility = View.GONE
            lHotArticle.visibility = View.GONE
            lHotInfo.visibility = View.GONE
            etSearch.hint = "请输入话题"
        }
    }

    //搜索所有页面的状态
    private fun onShowSearchAll() {
        mBinding.run {

            lSearchHistory.visibility = if (mViewModel.isHistoryEmpty()) View.GONE else View.VISIBLE

            if (mViewModel.mHotTopic.isEmpty()) {
                lHotTopic.visibility = View.GONE
            } else {
                mViewModel.mHotTopic.forEach {
                    lHotTopic.visibility = View.VISIBLE
                    val topicView = createFlowItem(it, true)
                    flowHotTopic.addView(topicView)
                    topicView.setOnClickListener(this@SearchActivity)
                }
            }

            if (mViewModel.mHotPost.isEmpty()) {
                lHotPost.visibility = View.GONE
            } else {
                mViewModel.mHotPost.forEach {
                    lHotPost.visibility = View.VISIBLE
                    val postView = createFlowItem(it)
                    flowPost.addView(postView)
                    postView.setOnClickListener(this@SearchActivity)
                }
            }

            if (mViewModel.mHotArticle.isEmpty()) {
                lHotArticle.visibility = View.GONE
            } else {
                mViewModel.mHotArticle.forEach {
                    lHotArticle.visibility = View.VISIBLE
                    val articleView = createFlowItem(it)
                    flowArticle.addView(articleView)
                    articleView.setOnClickListener(this@SearchActivity)
                }
            }

            if (mViewModel.mHotInformation.isEmpty()) {
                lHotInfo.visibility = View.GONE
            } else {
                mViewModel.mHotInformation.forEach {
                    lHotInfo.visibility = View.VISIBLE
                    val infoView = createFlowItem(it)
                    flowInfo.addView(infoView)
                    infoView.setOnClickListener(this@SearchActivity)
                }
            }

            //etSearch.hint = getString(R.string.string_input_keywords)
            etSearch.hint ="快来搜索看看呢…"
        }
    }

    override fun onBackPressed() {
        if (mSearchSuggestionsFragment.isVisible) {
            hideSuggestion()
            return
        }
        super.onBackPressed()
    }


    override fun initListener() {
        window.decorView.viewTreeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener)

        mBinding.tvClear.setOnClickListener {
            MessageNoticeDialog(message = "确认清除所有的历史记录吗？",
                cancelable = true,
                onConfirmClick = {
                    mViewModel.clearSearchHistory()
                }).show(supportFragmentManager)
        }

        mBinding.btnCancel.setOnClickListener {
            dismissKeyboard()
            finish()
        }

        mBinding.etSearch.setOnEditorActionListener { _, code, _ ->
            if (code == EditorInfo.IME_ACTION_SEARCH) {
                //只显示话题时，不跳转
                if (mViewModel.mKeywords.value.isEmpty() || mOnlyTopic) {
                    return@setOnEditorActionListener true
                }
                //SearchRetActivity.jump(mViewModel.mKeywords.value)
                hideSuggestion()
                //添加新的记录
                mViewModel.addSearchHistory(mViewModel.mKeywords.value)
                return@setOnEditorActionListener true
            }
            false
        }

        mViewModel.mKeywords.observeWithLifecycle(this) {
            if (it.trim().isEmpty()) {
                if (mSearchSuggestionsFragment.isVisible)
                    hideSuggestion()
            } else {
                if (!mSearchSuggestionsFragment.isVisible) {
                    showSuggestion()
                }

            }
        }
        mViewModel.mSearchHistoryData.observeWithLifecycle(this) {
            if (it.isEmpty())
                mBinding.lSearchHistory.visibility = View.GONE
            else {
                mBinding.lSearchHistory.visibility = View.VISIBLE
                updateSearchHistory(it)
            }
        }

        mViewModel.mSearchHotDataEvent.observeWithLifecycle(this) {
            when (it) {
                is Success -> {
                    if (mOnlyTopic) onShowSearchTopic() else onShowSearchAll()
                }
                else -> {

                }
            }
        }

        mViewModel.mSearchSuggestionEvent.observeWithLifecycle(this) {
            when (it) {
                is Loading -> {
                    mSearchSuggestionsFragment.onLoading()
                }
                is Success -> {
                    mSearchSuggestionsFragment.onSuccess(mViewModel.mKeywords.value)
                    //Log.d("sss", mViewModel.mKeywords.value)
                    mSearchSuggestionsFragment.setNewData(mViewModel.mSuggestionList)

                }
                is Failed -> {
                    if (it.message == "暂无数据内容") {
                        mSearchSuggestionsFragment.clearData()
                    }
                    mSearchSuggestionsFragment.onError(it.message)
                }
                else -> {

                }
            }
        }

        //选中搜索建议
        observeEvent<SearchSuggestionEvent> {
            if (it.suggestion.socialType == 4) {
                if (mOnlyTopic) {
                    //发布时选中话题
                    postEvent(SelectPostTopicEvent(it.suggestion.keyword, it.suggestion.socialId))
                    finish()
                } else {
                    //TopicActivity.jump(it.suggestion.socialId, "#${it.suggestion.keyword}#")
                }
            } else {
                mViewModel.addSearchHistory(it.suggestion.keyword)
                when (it.suggestion.socialType) {
                    MySocialConfig.POST -> {
                        //PostDetailsActivity.jump(it.suggestion.socialId)
                    }
                    MySocialConfig.ARTICLE -> {
                       // ArticleDetailsActivity.jump(it.suggestion.socialId)
                    }
                    MySocialConfig.GUIDE -> {
                       // GuideDetailsActivity.jump(it.suggestion.socialId)
                    }
                    MySocialConfig.INFORMATION -> {
                        //InformationDetailActivity.jump(it.suggestion.socialId)
                    }
                }
            }
        }
    }

    override fun onPause() {
        hideKeyboard(mBinding.etSearch)
        super.onPause()
    }

    override fun initData() {
        mBinding.viewModel = mViewModel
        //获取搜索记录
        mViewModel.getSearchHistory()
        //获取热门搜索
        mViewModel.getSearchHotData()
        //搜索建议
        mViewModel.getSearchSuggestion()
    }


    //显示搜索记录
    private fun updateSearchHistory(list: List<String>) {
        mBinding.run {
            if (list.isEmpty()) {
                flowSearchHistory.visibility = View.GONE
                return
            }
            if (flowSearchHistory.visibility != View.VISIBLE)
                flowSearchHistory.visibility = View.VISIBLE
            flowSearchHistory.removeAllViews()
            list.forEach {
                val historyView = createFlowItem(HotListItem("", it, HotListType.HISTORY))
                flowSearchHistory.addView(historyView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                historyView.setOnClickListener(this@SearchActivity)
            }
        }

    }

    private fun createFlowItem(item: HotListItem, isTopic: Boolean = false): TextView {
        val textView = TextView(this)
        textView.includeFontPadding = true
        if (isTopic)
            textView.text = "#${item.name}#"
        else
            textView.text = item.name
        textView.setTextColor(ContextCompat.getColor(this, mTextColorResId))
        //textView.paint.textSize = 14f.sp
        textView.paint.textSize = 14f.dp
        textView.maxWidth = 251.dp
        textView.tag = item
        textView.maxLines = 1
        textView.ellipsize = TextUtils.TruncateAt.END
        textView.setBackgroundResource(R.drawable.shape_search_history_tab_4dp)
        return textView
    }


    //根据键盘是否弹出，重设搜索建议的fragment高度
    private val mGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
        val r = Rect()
        //获取当前窗口实际的可见区域
        window.decorView.getWindowVisibleDisplayFrame(r)
        val height: Int = r.height()
        if (mWindowHeight == 0) {
            //一般情况下，这是原始的窗口高度
            mWindowHeight = height
        } else {
            var softKeyboardHeight = 0
            if (mWindowHeight != height) {
                //两次窗口高度相减，就是软键盘高度
                softKeyboardHeight = mWindowHeight - height
            }
            val fragment = supportFragmentManager.findFragmentByTag(SearchSuggestionsFragment.TAG) as SearchSuggestionsFragment?
            if (fragment != null && fragment.isVisible) {
                val l = fragment.getFragmentParentView().layoutParams
                l.height = mBinding.lContainer.height - softKeyboardHeight
                fragment.getFragmentParentView().layoutParams = l
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        window.decorView.viewTreeObserver.removeOnGlobalLayoutListener(mGlobalLayoutListener)
    }

    override fun onClick(p0: View?) {
        val hotListItem = p0?.tag as HotListItem
        when (hotListItem.type) {
            is HotListType.HISTORY -> {
                //跳转搜索结果页面
                //SearchRetActivity.jump(hotListItem.name)
                hideKeyboard(mBinding.etSearch)
                hideSuggestion()
            }
            is HotListType.TOPIC -> {
                //TopicActivity.jump(hotListItem.id, "#${hotListItem.name}#")
                mViewModel.addSearchHistory("#${hotListItem.name}#")
                hideSuggestion()
            }
            is HotListType.POST -> {
                //PostDetailsActivity.jump(hotListItem.id)
                mViewModel.addSearchHistory(hotListItem.name)
                hideSuggestion()
            }
            is HotListType.ARTICLE -> {
                //ArticleDetailsActivity.jump(hotListItem.id)
                mViewModel.addSearchHistory(hotListItem.name)
                hideSuggestion()
            }
            is HotListType.INFORMATION -> {
                //InformationDetailActivity.jump(hotListItem.id)
                mViewModel.addSearchHistory(hotListItem.name)
                hideSuggestion()
            }
        }
    }

    private fun showSuggestion() {
        supportFragmentManager.beginTransaction().show(mSearchSuggestionsFragment).commitAllowingStateLoss()
    }

    private fun hideSuggestion() {

        supportFragmentManager.beginTransaction().hide(mSearchSuggestionsFragment).commitAllowingStateLoss()

    }


}